package com.flow.framework.schedule.service.system.health.impl;

import com.flow.framework.common.health.ServiceHealthCheckCode;
import com.flow.framework.common.pojo.vo.system.ServiceHealthVo;
import com.flow.framework.common.service.system.health.IHealthCheckService;
import com.flow.framework.common.util.verify.VerifyUtil;
import com.flow.framework.core.system.helper.SystemHealthHelper;
import com.flow.framework.schedule.job.BaseScheduleJob;
import lombok.extern.slf4j.Slf4j;

import java.util.*;

/**
 * 调度任务健康检查
 *
 * @author luoguopiao
 * @version 0.0.1
 * @date 2022/4/10
 */
@Slf4j
public class ScheduleJobHealthCheckServiceImpl implements IHealthCheckService {

    private static final String JOB_NAME_AND_CLAZZ_SEPARATOR = "-";

    @Override
    public List<ServiceHealthVo> check() {
        Map<String, String> executeFailedJobNameAndClazzName = BaseScheduleJob.getExecuteFailedJobNameAndClazzName();
        try {
            if (VerifyUtil.isEmpty(executeFailedJobNameAndClazzName)) {
                return Collections.singletonList(SystemHealthHelper.healthy(ServiceHealthCheckCode.ASYNC_SCHEDULE_HEALTH_CHECK_CODE));
            }
            Set<String> unHealthJobNameAndClazz = new HashSet<>();
            executeFailedJobNameAndClazzName.forEach((key, value) -> {
                unHealthJobNameAndClazz.add(key + JOB_NAME_AND_CLAZZ_SEPARATOR + value);
            });
            return Collections.singletonList(SystemHealthHelper.unhealthy(ServiceHealthCheckCode.SERVICE_DATABASE_CODE,
                    "schedule job occurred error", new ArrayList<>(unHealthJobNameAndClazz)));
        } catch (Exception e) {
            log.error("check schedule job error.", e);
            return Collections.singletonList(
                    SystemHealthHelper.unhealthy(ServiceHealthCheckCode.SERVICE_DATABASE_CODE, e.getMessage(), null)
            );
        }
    }
}
